package com.palazzisoft.balonpie.provider;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.palazzisoft.balonpie.dao.UserDao;
import com.palazzisoft.balonpie.entities.User;

@Component
public class BalonpieAuthenticationProvider implements AuthenticationProvider {

	private UserDao userDao;

	@Autowired
	public BalonpieAuthenticationProvider(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {

		UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

		String username = token.getName();

		User userToBeAuthenticated = null;

		if (username != null) {
			userToBeAuthenticated = userDao.getUser(username);
		}

		if (userToBeAuthenticated == null) {
			throw new UsernameNotFoundException("Invalid User");
		}

		this.validatePassword(userToBeAuthenticated, token);

		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(userToBeAuthenticated.getRole());

		return new UsernamePasswordAuthenticationToken(userToBeAuthenticated.getUserName(),
				userToBeAuthenticated.getPassword(), authorities);

	}

	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class.equals(authentication);

	}

	private void validatePassword(User user, UsernamePasswordAuthenticationToken token) {
		if (!user.getPassword().equals(token.getCredentials())) {
			throw new BadCredentialsException("Authentication Error");
		}
	}
}
